/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package is202.hrms.web;

import is202.hrms.ejb.ForelesningEJB;
import is202.hrms.entity.Forelesning;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;
import javax.inject.Named;

/**
 *
 * @author Sondre
 */
@Named("forelesningconverter") @RequestScoped
@FacesConverter(forClass=Forelesning.class)
public class ForelesningConverter implements Converter {

    @EJB
    ForelesningEJB forelEjb;

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        long forelesningId = Long.parseLong(value);
        if (null == forelEjb) {
            System.out.println("No EJB!");
            throw new ConverterException("No EJB!");
        }
        Forelesning forelesning = forelEjb.find(forelesningId);
        if (null == forelesning) {
            System.out.println("No value!");
            throw new ConverterException("Cannot convert \""+value+"\" to Department");
        }
        return forelesning;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (null != value && value instanceof Forelesning) {
            Forelesning forelesning = (Forelesning)value;
            return ""+forelesning.getForelesningNr();
        }
        throw new ConverterException("Illegal value - must be a Department object");
    }

}
